#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
讯飞语音转写服务启动脚本
"""

import os
import sys
from app import app
from config import config

def check_environment():
    """检查环境配置"""
    required_vars = ['XFYUN_APPID', 'XFYUN_API_KEY', 'XFYUN_API_SECRET']
    missing_vars = []
    
    for var in required_vars:
        if not os.environ.get(var):
            missing_vars.append(var)
    
    if missing_vars:
        print("⚠️  警告: 以下环境变量未设置:")
        for var in missing_vars:
            print(f"  - {var}")
        print("\n请设置环境变量或在 config.py 中配置默认值")
        print("获取讯飞开放平台凭证: https://www.xfyun.cn/")
        return False
    
    return True

def main():
    """主函数"""
    # 获取运行环境
    env = os.environ.get('FLASK_ENV', 'development')
    config_class = config.get(env, config['default'])
    
    # 应用配置
    app.config.from_object(config_class)
    
    print("🚀 启动讯飞语音转写服务...")
    print(f"🌍 运行环境: {env}")
    print(f"📁 上传目录: {config_class.UPLOAD_FOLDER}")
    print(f"📊 日志级别: {config_class.LOG_LEVEL}")
    
    # 检查环境变量
    if not check_environment():
        print("\n💡 提示: 你可以通过以下方式设置环境变量:")
        print("  Linux/Mac: export XFYUN_APPID='your_appid'")
        print("  Windows: set XFYUN_APPID=your_appid")
        print("  或在 config.py 中直接修改默认值")
    
    # 创建上传目录
    os.makedirs(config_class.UPLOAD_FOLDER, exist_ok=True)
    
    # 启动服务
    try:
        app.run(
            host='0.0.0.0',
            port=int(os.environ.get('PORT', 5000)),
            debug=config_class.DEBUG,
            threaded=True
        )
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {str(e)}")
        sys.exit(1)

if __name__ == '__main__':
    main()
